# @author:Wei Junjie
# @time:2024/5/17 15:27
# @file demo01.py
# --*--coding: utf-8 --*--
"""
https://skrbttx 爬取案例
"""
import os
import time
import random
import re
from urllib import parse
import requests
from fake_useragent import UserAgent
import csv

TEXT_PATH=os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'sourceStore','TEXT')

class skrBT:
    def __init__(self, tet, tesm):
        self.tet = tet
        self.tesm = tesm
        # cookie加密
        self.baseUrl = 'https://skrbttx.top'

    def search_keywords(self,name:str,page:int,ways:str)->object:
        cookie = {
            'aywcUid': 'ouRTJ7iGqQ_20240517111318',
            'tcv': 'V4',
            # 可设固定值
            'tet': self.tet,
            'tetm': self.tesm,
        }
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'referer': 'https://skrbttx.top/recaptcha/v4/challenge?url=https://skrbttx.top&s=1',
        }
        params = {
            'keyword': name,
            'p': page
        }
        try:
            response = requests.get(self.baseUrl+ways,
                                params=params,
                                cookies=cookie,
                                headers=headers)
            if name not in response.text:
                print('你输入的tet或tetm的值与服务器不匹配请重新输入')
            else:
                return response
        except Exception as e:
            print(e)

    def detail_content(self,pattern:str,content:str)->list:
        re_obj = re.findall(pattern,content)
        return re_obj

    def get_BT(self,name:str,page:int,ways:str)->object:
        ua=UserAgent()
        name=parse.quote(name)
        cookie = {
            'aywcUid': 'ouRTJ7iGqQ_20240517111318',
            'tcv': 'V4',
            # 可设固定值
            'tet': self.tet,
            'tetm': self.tesm,
        }
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'referer': 'https://skrbttx.top/search?keyword={}&sos=relevance&sofs=all&sot=all&soft=all&som=exact&p={}'.format(name,page)
        }
        response = requests.get(self.baseUrl+ways,
                                cookies=cookie,
                                headers=headers)
        return response

    def write_BT(self,name:str,page:int,content:str)->None:
        patten='<title>(.*)</title>.*(magnet:\?xt=urn:btih:\w+)'
        res=re.findall(patten,content)
        print(res)
        # title,data=res[0][0].strip(' - 磁力链接与种子下载'),res[0][1]
        # with open(TEXT_PATH+name+str(page)+"页.txt",'a',encoding='utf-8') as  f:
        #     f.write(title+","+data+"\n")

        # newline表示换行符
        with open(TEXT_PATH + name + str(page) + "页.csv", 'a', encoding='UTF-8-sig',newline='') as c:
            writer = csv.writer(c)

            # 写多行
            # writer.writerows(res)

            # 写一行
            writer.writerow(list(*res))

    def main(self):
        name=input("请输入要你要搜索的演员名字:")
        start_page=int(input("请输入起始页码:"))
        end_page=int(input("请输入终止页码:"))
        for page in range(start_page,end_page+1):
            try:
                content=self.search_keywords(name,page,'/search').text
                methods = quchong(self.detail_content('/detail/\w+/\S*\w', content))
                print(methods)
                for method in methods:
                    try:
                        content2 = self.get_BT(name, page, method).text
                        if name not in content2:
                            continue
                        else:
                            self.write_BT(name, page, content2)
                            time.sleep(random.randint(1, 10))
                    except Exception as e:
                        print(e)
            except Exception as e:
                print(e)



#  数据库操作
class Mysql:
    pass


def quchong(ls):
    if not ls:
        return []
    first=ls[0]
    remain=ls[1:]
    # 不取
    if first in remain:
        return quchong(remain)
    # 取
    return [first]+quchong(remain)


if __name__ == "__main__":
    skrBT = skrBT('1716720501735','0E703')
    skrBT.main()